
import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/manage/HomeView.vue'
import ModelsView from '@/views/manage/ModelsView.vue'
import CarsView from '@/views/manage/CarsView.vue'
import IndexView from '@/views/manage/IndexView.vue'
import LoginView from '@/views/LoginView.vue'
import UserindexView from '@/views/client/UserindexView.vue'
import UserView from '@/views/client/UserView.vue'
import UserOrdersView from '@/views/client/UserOrdersView.vue'
import AdminUserView from '@/views/manage/AdminUserView.vue'
import OrdersView from '@/views/manage/OrdersView.vue'
import adminApi from '@/api/adminApi'
import { useTokenStore } from '@/stores/token';





const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    { 
      path:'/login',
      name:'login',
      component:LoginView
    },
    {
      path:'/user',
      name:'user',
      component:UserView,
      meta:{roles:['用户']},
      children:[
        {
          path:'/userindex',
          component:UserindexView,
          meta:{roles:['用户']}
        },
        {
          path:'/userorders',
          component:UserOrdersView,
          meta:{roles:['用户']}
        }
      ]
    },
    {
      path: '/',
      name: 'home',
      component: HomeView,
      redirect:'/index',
      meta:{roles:['管理员']},
      children:[//子路由，父路由的内容也会被渲染
        {
          path: '/Cars',
          component:CarsView,
          meta:{roles:['管理员']}

        },
        {
          path: '/models',
          component: ModelsView,
          meta:{roles:['管理员']}

        },
        {
          path: '/index',
          component:IndexView,
          meta:{roles:['管理员']}
        },
        {
          path: '/adminuser',
          component:AdminUserView,
          meta:{roles:['管理员']}
        },
        {
          path: '/adminorders',
          component:OrdersView,
          meta:{roles:['管理员']}
        },
      ]
     
    }, {
      path: '/about',
      name: 'about',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('../views/AboutView.vue')
    }
  ]
});
//导航守卫
// router.beforeEach((to,from)=>{
// //to-要访问的位置
// //from-起始位置
// if(to.path=='/login'){
//   return true;
// }else {
//   //判断sessionStorage中是否有token
//   if(!sessionStorage.getItem('token')){
//     //没有令牌
//     return '/login';
//   }else {
//     const user=ref('');
//     //有令牌
//     adminApi.longinfo()
//     .then(resp => {
//       user.value=resp.data.user;
//         //隐藏对话框
//     });
//     if(to.matched.some(record => record.meta.roles && record.meta.roles.includes(user))){
//       //用户角色放行
//       return true;
//     }
//     return '/userindex';
//   }
// }


// });

//导航守卫
  
router.beforeEach((to, from, next) => {  
  // 如果目标是登录页面，直接放行  
  if (to.path === '/login') {  
    next();  
  } else {  
    const tokenStore=useTokenStore();
    // 检查 sessionStorage 中是否有 token  
    const token = tokenStore.tokenStr;  
    if (!token) {  
      // 没有 token，重定向到登录页面  
      next('/login');  
    } else {  
      // 假设 adminApi.longinfo() 是一个返回 Promise 的 API 调用  
      adminApi.longinfo().then(resp => {  
        const userRole = resp.data.user; // 假设用户角色在 user.role 中  
  
        // 检查用户是否有权限访问目标路由  
        if (to.matched.some(record => record.meta.roles && record.meta.roles.includes(userRole))) {  
          // 用户有权限，放行  
          next();  
        } else {  
          // 用户没有权限，重定向到用户首页或其他页面  
          next('/userindex');  
        }  
      }).catch(error => {  
        // 处理 API 调用失败的情况  
        console.error('API 调用失败:', error);  
        // 可以选择重定向到错误页面或登录页面  
        next('/login');  
      });  
    }  
  }  
});  
  


export default router
